package cn.roadtrip.mtravelbusinessmodule.bs.basic;

import cn.roadtrip.mtravelbusinessmodule.sql.couple.tables.records.BsUserlayoutCityRecord;
import cn.roadtrip.mtravelbusinessmodule.sql.couple.tables.records.BsUserlayoutSchoolRecord;
import cn.roadtrip.mtravelbusinessmodule.sql.couple.tables.records.BsUserlayoutUserinforRecord;
import cn.roadtrip.utilmodule.util.DataBean;
import cn.roadtrip.utilmodule.wechat.MiniPromUtil;
import com.github.yitter.idgen.YitIdHelper;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import lombok.*;
import org.jooq.DSLContext;
import org.jooq.impl.DSL;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;

import static cn.roadtrip.mtravelbusinessmodule.sql.couple.tables.BsUserlayoutCity.BS_USERLAYOUT_CITY;
import static cn.roadtrip.mtravelbusinessmodule.sql.couple.tables.BsUserlayoutSchool.BS_USERLAYOUT_SCHOOL;
import static cn.roadtrip.mtravelbusinessmodule.sql.couple.tables.BsUserlayoutUserinfor.BS_USERLAYOUT_USERINFOR;
import static cn.roadtrip.mtravelbusinessmodule.sql.couple.tables.CoupleSchool.COUPLE_SCHOOL;
import static cn.roadtrip.mtravelbusinessmodule.sql.couple.tables.SysCategory.SYS_CATEGORY;
import static cn.roadtrip.utilmodule.util.DataBean.err;
import static cn.roadtrip.utilmodule.util.DataBean.suc;

/**
 * 用户信息操作
 */
@Component
public class UserInforImpl {
    @Autowired
    private DSLContext dslContext;

    @Data
    @Builder
    @AllArgsConstructor
    @NoArgsConstructor
    @EqualsAndHashCode
    public static class Model_saveSelfProfile {
        private String userId;
        private String phone;
        private String nickName;
        private String idCard;
        private String cover;
        private String schoolId;
        private String cityId;
        private java.util.Map<String, Object> extInfors;
    }

    /**
     * 保存个人信息
     *
     * @param model
     * @return
     */
    public DataBean saveSelfProfile(
            Model_saveSelfProfile model
    ) {
        try {
            return dslContext.transactionResult(ctx -> {
                BsUserlayoutUserinforRecord userModel = dslContext.selectFrom(
                        BS_USERLAYOUT_USERINFOR
                ).where(BS_USERLAYOUT_USERINFOR.ID.eq(model.getUserId())).fetchOne();

                if (userModel == null) {
                    return err("user-not-exist", "用户不存在");
                }
                Gson gson = new Gson();
                if (userModel.getPhone().length() < 10) {
                    userModel.setPhone(model.getPhone());
                }
                userModel.setNickname(model.getNickName());
                if (userModel.getIdcard().length() < 10) {
                    userModel.setIdcard(model.getIdCard());
                }
                userModel.setCover(model.getCover());
                userModel.setExtinfors(gson.toJson(model.getExtInfors()));
                userModel.update();

                //更新绑定学校
                {
                    BsUserlayoutSchoolRecord school = dslContext.selectFrom(
                            BS_USERLAYOUT_SCHOOL
                    ).where(
                            BS_USERLAYOUT_SCHOOL.USER_ID.eq(model.getUserId())
                    ).fetchOne();
                    if (school == null) {
                        dslContext.insertInto(BS_USERLAYOUT_SCHOOL).set(
                                new BsUserlayoutSchoolRecord(
                                        YitIdHelper.nextId() + "",
                                        null,
                                        null,
                                        null,
                                        null,
                                        null,
                                        null,
                                        null,
                                        model.getUserId(),
                                        model.getSchoolId()
                                )
                        ).execute();
                    } else {
                        school.setSchoolId(model.getSchoolId());
                        school.update();
                    }
                }
                //更新绑定城市
                {
                    BsUserlayoutCityRecord city = dslContext.selectFrom(
                                    BS_USERLAYOUT_CITY
                            ).where(BS_USERLAYOUT_CITY.USER_ID.eq(model.getUserId()))
                            .fetchOne();
                    if (city == null) {
                        dslContext.insertInto(BS_USERLAYOUT_CITY).set(
                                new BsUserlayoutCityRecord(
                                        YitIdHelper.nextId() + "",
                                        null,
                                        null,
                                        null,
                                        null,
                                        null,
                                        null,
                                        "0",
                                        model.getUserId(),
                                        model.getCityId()
                                )
                        ).execute();
                    } else {
                        city.setCityId(model.getCityId());
                        city.update();
                    }
                }


                dslContext.commit();
                return suc(true, 1, "suc", "操作成功");
            });
        } catch (Exception e) {
            e.printStackTrace();
            return err("trans-err", e.getMessage());
        }
    }

    @Data
    @Builder
    @AllArgsConstructor
    @NoArgsConstructor
    @EqualsAndHashCode
    public static class Model_getSelfProfile {
        private String userId;
    }

    @Data
    @Builder
    @AllArgsConstructor
    @NoArgsConstructor
    @EqualsAndHashCode
    public static class VPO_getSelfProfile {
        private String id;
        private String stats;
        private String phone;
        private String nickName;
        private String sex;
        private Long createTime;
        private Long lastLoginTime;
        private String idCard;
        private String tenantId;
        private String cover;
        private String strextInfors;
        private java.util.Map<String, Object> extInfors;
        private String cityTitle;
        private String cityId;
        private String schoolTitle;
        private String schoolId;
        private String roleType;
    }

    /**
     * 获取自己得信息
     *
     * @param model
     * @return
     */
    public DataBean getSelfProfile(
            Model_getSelfProfile model
    ) {
        try {
            return dslContext.transactionResult(ctx -> {
                //todo

                VPO_getSelfProfile userModel = dslContext.select(
                                DSL.field("t.id").as("id"),
                                DSL.field("t.stats").as("stats"),
                                DSL.field("t.phone").as("phone"),
                                DSL.field("t.nickName").as("nickName"),
                                DSL.field("t.sex").as("sex"),
                                DSL.field("t.createTime").as("createTime"),
                                DSL.field("t.lastLoginTime").as("lastLoginTime"),

                                DSL.field("t.idCard").as("idCard"),
                                DSL.field("t.tenantId").as("tenantId"),
                                DSL.field("t.cover").as("cover"),
                                DSL.field("t.extInfors").as("strextInfors"),
                                DSL.ifnull(SYS_CATEGORY.NAME, "nil").as("cityTitle"),
                                DSL.ifnull(SYS_CATEGORY.ID, "nil").as("cityId"),
                                DSL.ifnull(COUPLE_SCHOOL.TITLE, "nil").as("schoolTitle"),
                                DSL.ifnull(BS_USERLAYOUT_SCHOOL.SCHOOL_ID, "nil").as("schoolId"),
                                DSL.ifnull(DSL.field("BS_UserLayout_UserBindRole.roleType"), "nil").as("roleType")
                        ).from(
                                DSL.selectFrom(
                                                BS_USERLAYOUT_USERINFOR
                                        ).where(BS_USERLAYOUT_USERINFOR.ID.eq(model.getUserId()))
                                        .asTable("t")
                        )
                        .leftJoin(BS_USERLAYOUT_CITY)
                        .on(BS_USERLAYOUT_CITY.USER_ID.eq(DSL.field("t.id", String.class)))
                        .leftJoin(BS_USERLAYOUT_SCHOOL)
                        .on(BS_USERLAYOUT_SCHOOL.USER_ID.eq(DSL.field("t.id", String.class)))
                        .leftJoin(SYS_CATEGORY)
                        .on(SYS_CATEGORY.ID.eq(BS_USERLAYOUT_CITY.CITY_ID))
                        .leftJoin(COUPLE_SCHOOL)
                        .on(COUPLE_SCHOOL.ID.eq(BS_USERLAYOUT_SCHOOL.SCHOOL_ID))
                        .leftJoin("BS_UserLayout_UserBindRole")
                        .on("BS_UserLayout_UserBindRole.userId = t.id")
                        .limit(1)
                        .fetchOneInto(VPO_getSelfProfile.class);

                if (userModel == null) {
                    return err("user-not-exist", "用户不存在");
                }

                userModel.setExtInfors(new Gson().fromJson(userModel.getStrextInfors(), new TypeToken<Map<String, Object>>() {
                }.getType()));


                dslContext.commit();
                return suc(userModel, 1, "suc", "操作成功");
            });
        } catch (Exception e) {
            e.printStackTrace();
            return err("trans-err", e.getMessage());
        }
    }


    @Data
    @Builder
    @AllArgsConstructor
    @NoArgsConstructor
    @EqualsAndHashCode
    public static class Model_getWchatTelByCode {
        private String telCode;
    }


    @Autowired
    private MiniPromUtil miniPromUtil;

    /**
     * 获取微信手机号
     *
     * @param model
     * @return
     */
    public DataBean getWchatTelByCode(
            Model_getWchatTelByCode model
    ) {
        try {

            String tel = miniPromUtil.getPhoneNum(model.getTelCode());
            if (tel == null) {
                return DataBean.err("tel-err", "获取手机号错误");
            }
            return DataBean.suc(tel, 1, "suc", "操作成功");
        } catch (Exception e) {
            e.printStackTrace();
            return DataBean.err("trans-err", e.getMessage());
        }
    }
}
